package de.islanders.shared;

import java.lang.Thread.State;
import java.util.HashMap;
import java.util.Map;

public class ThreadManager {
	private static ThreadManager mgr;
	private HashMap<String, Thread> threads;
	private int numRunningThreads;
	
	private ThreadManager(){
		threads = new HashMap<String, Thread>();
	}
	
	public static ThreadManager getInstance(){
		if(mgr == null){
			mgr = new ThreadManager();
		}
		return mgr;
	}
	
	public void startAllThreads(){
		for(Map.Entry<String, Thread> entry : threads.entrySet()){
			if(!entry.getValue().isAlive()){
				entry.getValue().start();
				numRunningThreads++;
			}
		}
	}
	
	public void killAllThreads(){
		for(Map.Entry<String, Thread> entry : threads.entrySet()){
			if(entry.getValue().isAlive()){
				entry.getValue().interrupt();
				numRunningThreads--;
			}
		}
	}
	
	public boolean startThread(String name){
		if(!threads.get(name).isAlive()){
			threads.get(name).start();
			numRunningThreads++;
		} 
		return threads.get(name).isAlive();
	}
	
	public boolean killThread(String name){
		if(threads.get(name).isAlive()){
			threads.get(name).interrupt();
			numRunningThreads--;
		} 
		return !threads.get(name).isAlive();
	}
	
	public Thread getThread(String name){
		return threads.get(name);
	}
	
	public State getState(String name){
		return threads.get(name).getState();
	}
	
	public int getNumRunningThreads(){
		return numRunningThreads;
	}
	
	public int getNumThreadsInCache(){
		return threads.size();
	}
	
	public void addThread(String name, Thread thread){
		thread.setName(name);
		threads.put(name, thread);
	}
	
	public void removeThread(String name){
		threads.remove(name);
	}
}
